﻿using Datas;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEngine.SceneManagement;


public class SaveManager : SingletonMono<SaveManager>
{
    private GameData gameData;
    private FileDataHandler dataHandler;
    [SerializeField] private string fileName= "ycemc.alexdev";
    [SerializeField] private bool encrypt;
    [SerializeField] private List<ISaveManager> saveManagers;

    void Start()
    {
        dataHandler = new FileDataHandler(Application.persistentDataPath, fileName, encrypt);
        saveManagers = FindAllInstancesOf<ISaveManager>();
        saveManagers.Add(PlayerManager.Instance);
        LoadGame();
    }


    public List<T> FindAllInstancesOf<T>() where T : class
    {
        List<T> result = new List<T>();
        // 查找项目中所有继承某个接口且继承mono的实例(需要挂载)
        result.AddRange(FindObjectsOfType<MonoBehaviour>().OfType<T>());

        return result;
    }

    public void NewGame()
    {
        gameData = new GameData();
    }


    public void LoadGame() 
    {
        gameData = dataHandler.LoadData();

        if(gameData == null)
        {
            Debug.Log("没有保存的游戏数据。。");
            NewGame();
        }

        foreach(ISaveManager s in saveManagers)
        {
            s.LoadData(gameData);
        }

    }

    public void SaveGame() 
    {
        foreach (ISaveManager s in saveManagers)
        {
            s.SaveData(ref gameData);
        }
        dataHandler.SaveData(gameData);
    }

    private void OnApplicationQuit()
    {
        SaveGame();
    }


}

